/* eslint-disable no-async-promise-executor */
import { loginApi, logout, getInfoApi, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INFO: (state, userinfo) => {
    state.userInfo = userinfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginApi(userInfo)
        .then((response) => {
          commit('SET_TOKEN', response.data)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  // 获取用户信息
  // 并将用户信息存储在仓库
  getInfo({ commit, state }) {
    return new Promise(async(resolve, reject) => {
      try {
        /* 获取用户信息 */
        const { data } = await getInfoApi()
        /* 根据用户id获取用户图像信息 */
        const res = await getUserDetailById(data.userId)
        commit('SET_NAME', data.username)
        commit('SET_INFO', data)
        /* 存储图片 */
        commit('SET_AVATAR', res.data.staffPhoto)
        resolve(data)
      } catch (error) {
        reject(error)
      }
      // getInfoApi()
      //   .then((response) => {
      //     const { data } = response

      //     commit('SET_NAME', data.username)
      //     commit('SET_INFO', data)
      //     resolve(data)
      //   })
      //   .catch((error) => {
      //     reject(error)
      //   })
    })
  },

  // user logout
  // 退出删除用户令牌
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
